<?php

class Client_Table_Tags extends Apk_Db_Table
{
	protected $_name      = 'tags';
    protected $_primary   = 'id';
    public $_ERROR = '';
    
    protected $max_size = 22;
    protected $min_size = 8;

    public function GetError()
    {
    	return $this->_ERROR;
    }
    
    public function GetDataList()
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('is_active');    				

    	return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }     
    
    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('id = ?', $id)->assemble();    	    	

    	return $this->getList($sel)->getRow(0)->toArray();
    }      
    
    public function GetArticlesTags($limit = 20)
    {
		$sel = $this->getAdapter()->select()
					->from('tags_to_articles')
					->joinInner('tags', 'tags.id = tags_to_articles.id_tag', array('id', 'name', 'count_articles'))
					->where('tags.is_active')
					->order('tags.count_articles desc')
					->group('tags.id')
					->limit($limit);
										
		$a = $this->getList($sel)->toArray();

		if(!(count($a) > 0)) return;

		$max = $a[0]['count_articles'];
		if(!($max > 0)) return array();
		
		$min = $a[count($a)-1]['count_articles'];		
		
		$a = $this->array_rand($a);
		//usort($a, "cmp");
		
		$kf = $this->max_size/$max; 
		
		foreach ($a as $k=>$v)	
		{
			$a[$k]['size'] = $v['count_articles']*$kf;
		}

		return $a;
    }     
   

    public function array_rand($a)
    {
		if(!is_array($a)) return;

    	srand($this->make_seed());
		$r = array();
		while(count($r) != count($a))
		{
			$s = rand(0, count($a)-1);
			if(!in_array($s, $r)) $r[] = $s;
		}

		$ret = array();
		foreach($r as $v)
			$ret[] = $a[$v];

		return $ret;
    }

	function make_seed() {
	    list($usec, $sec) = explode(' ', microtime());
	    return (float) $sec + ((float) $usec * 100000);
	}
	
	function cmp($a, $b){
		return strcmp($a["name"], $b["name"]);
	}
	
    public function GetTagByName($tag)
    {
		$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->where('name = ?', $tag);
					
		$data = $this->getList($sel)->toArray();		
		
		if(count($data) > 0) return $data[0]['id'];
		else return 0;					
    } 
    
    public function SearchTagsByName($tag)
    {
		$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->where("name like '".$tag."%'")
					->where('is_active')
					->order('name')
					->limit(10);
					
		return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();					
					
    }     
           
    public function GetTagsByObjId($object_name = 'articles', $object_id)
    {
        $table_name = 'tags_to_'.$object_name;
        $table_field_name = 'id_'.$object_name;

    	$sel = $this->getAdapter()->select()
					->from($this->_name, array('id', 'name'))
					->join($table_name, $table_name.'.id_tag = tags.id')
					->where($table_name.'.'.$table_field_name.' = ?', $object_id);					
							
		return $this->getList($sel)->toArray();				
    } 
    
    public function GetTagsStringByObjId($object_name = 'articles', $object_id)
    {
		$tags = $this->GetTagsByObjId($object_name, $object_id);
		
		$ret = '';		
		foreach ($tags as $tag) 
		{
			if($ret != '') $ret .= ', ';
			$ret .= $tag['name'];
		}
		return $ret;
    }    
	
	
	public function insertStr($tags_str, $object_name = 'articles', $object_id, $user_id)
    {
        $table_name = 'tags_to_'.$object_name;
        $table_field_name = 'id_'.$object_name;
        
    	$tags_arr = explode(',', $tags_str);
    	
    	$this->getAdapter()->delete($table_name, $table_field_name.' = '.$object_id);
        
        if(count($tags_arr) > 0)  
        foreach($tags_arr as $tag) {        	
        	$tag = trim($tag);
        	
        	if($tag == '') continue;
        	
        	$tag_id = $this->GetTagByName($tag);
        	
        	if($tag_id == 0){ 
        		$d = array();       	
	        	$d['name'] = $tag;
	        	$d['add_date'] = time();
	        	$d['modify_date'] = time();
	        	$d['add_user_id'] = $user_id;
	        	$d['modify_user_id'] = $user_id;
	        	
	        	try{
	        		$tag_id = parent::insert($d);
	        	}catch (Exception $e){
	        		//echo 'hello'; die();
	        	}
        	}        	

        	if($tag_id > 0)	 
        	{
        	   $d = array(
        	      'id_tag' => $tag_id,
        	      $table_field_name => $object_id
        	   );
        	   
        	   try{
        	   		$this->getAdapter()->insert($table_name, $d);
	        	}catch (Exception $e){
	        		//echo 'hello'; die();
	        	}        	   		
        	}
        	
        }    			
    }
    
    public function update(array $data, $id)
    {
		return parent::update($data, 'id = '.$id);
    }	
	

    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }	


}
?>